import address from '../models/address.js';
import Response from '../utils/response.js';

const getByUserId = async function (ctx) {
  const user_id = ctx.params.user_id;
  const result = await address.getByUserId(user_id);

  const res = new Response(result);
  ctx.body = res;
};

const getById = async function (ctx) {
  const id = ctx.params.id;
  const result = await address.getById(id);

  const res = new Response(result);
  ctx.body = res;
};

const create = async function (ctx) {
  const data = ctx.request.body;
  const result = await address.create(data);

  const res = new Response(result);
  ctx.body = res;
};

const removeById = async function (ctx) {
  const id = ctx.params.id;
  const result = await address.removeById(id);

  ctx.body = new Response();
};

const updateById = async function (ctx) {
  const id = ctx.params.id;
  const data = ctx.request.body;

  if (parseInt(id, 10) !== data.id) {
    ctx.body = new Response(null , 1, 'Can\'t modify another key.');
    return;
  }
  const result = await address.updateById(data);

  ctx.body = new Response(result);
};

export default {
  getByUserId,
  getById,
  create,
  removeById,
  updateById
};
